<?php

class CoffeeShopController extends Controller
{
	public $thumbWidth=185;
	public $thumbHeight=200;
	public $imageWidth=572;
	public $imageHeight=700;
	public $imageFolder='shop';
	public $thumbFolder='tn';

	public $twitterOnUpdate=false;



	/**
	 * @var string the default layout for the views. Defaults to 'column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='column2';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('listAll','viewShop'),
				'users'=>array('*'),
		),
		array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('vote'),
				'users'=>array('@'),
		),
		array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','admin','create','update','approve','list','view','delete'),
				'roles'=>array('cafeAdmin'),
		),
		array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('uploadImage','manageImages','deleteImage'),
				'roles'=>array('photoManager'),
		),
		array('allow','actions'=>array('uploadImage','manageImages','deleteImage','ownerUpdate'),
				'roles'=>array('cafeOwner')),
		array('allow',
					'actions'=>array('quickCreateUser','quickCreate','ajaxQuickSearch','ajaxQuickSearchUser','ajaxQuickSearchHasOwner'),
					'roles'=>array('cafeAdmin'),//User::getAdmins(),
		),
		array('allow', // Only allow admin to export file.
			'actions'=>array('exportFile'),
			'users'=>array('admin'),
		),
		array('deny',  // deny all users
				'users'=>array('*'),
		),
		);
	}

	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$this->render('view',array(
			'model'=>$this->loadModel(),
		));
	}


	public function actionVote(){
		$model=$this->loadModel();
		if(Yii::app()->request->isPostRequest){

			if(CafeVote::vote($model->id,CafeVote::FROM_WEB,Yii::app()->user->getId(),$_SERVER['REMOTE_ADDR'])){
				$message='You have successfully voted '.$model->name.'.';
			}else{
				$message='You can vote only once for '.$model->name.'.';
			}
			Yii::app()->user->setFlash('vote',$message);
		}
		$this->redirect(array('viewShop','id'=>$model->id));

	}

	public function actionViewShop()
	{

		//		if(isset($_GET['id']))
		//			$model=CoffeeShop::model()->with('voteToday','voteThisWeek','voteAll')->findbyPk($_GET['id']);
		//		if($model===null)
		//			throw new CHttpException(404,'The requested page does not exist.');
		$model=$this->loadModel();

		$this->render('viewShop',array(
			'model'=>$model,
			'voted'=>!Yii::app()->user->getIsGuest()&&CafeVote::voted($model->id,Yii::app()->user->getId()),
			'voteOn'=>Yii::app()->params['mcrVote'],
			'votePeriod'=>Yii::app()->params['mcrVotePeriod'],
		));
	}

	public function actionListAll(){
		$model=CoffeeShop::model()->showWeb();
		if(isset($_GET['CoffeeShop']))
		$model->attributes=$_GET['CoffeeShop'];

			
		$model->showWeb=1;
		$dataProvider=$model->frontEndSearch();
		$pagination=$dataProvider->getPagination();
		$pagination->setPageSize(20);

		if(count($dataProvider->getData())==0){
			$url=array('coffeeRecommend/recommend');
			if(isset($_GET['CoffeeShop'])){
				if(isset($_GET['CoffeeShop']['name'])){
					$url['name']=$_GET['CoffeeShop']['name'];
				}
				if(isset($_GET['CoffeeShop']['suburb'])){
					$url['suburb']=$_GET['CoffeeShop']['suburb'];
				}
			}
			$message='This café is not on our database, if you would like to enter it please '.CHtml::link('click here', $url);
			Yii::app()->user->setFlash('search',$message);
		}


		$this->render('frontEndList',array(
			'model'=>$model,
			'dataProvider'=>$dataProvider,
		));
	}

	//	public function actionList()
	//	{
	//		$model=CoffeeShop::model()->showWeb()->highrating();
	//		$this->render('list',array(
	//			'model'=>$model,
	//		));
	//
	//
	//	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new CoffeeShop;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['CoffeeShop']))
		{
			$model->attributes=$_POST['CoffeeShop'];

			if(isset($_POST['geo'])){
				$address=$model->street.', '.$model->suburb.' '.$model->state.', '.$model->postcode.', '.$model->country;
				$geo=Yii::app()->google->getGeoCode($address);
				if($geo['status']=='OK'){
					$result=$geo['results'][0];
					$oldAddress=$model->street.', '.$model->suburb.' '.$model->postcode.' '.$model->state.', '.$model->country
					.'. Location: '.$model->latitude.' '.$model->longitude;
					$streetNo='';
					$street='';
					foreach($result['address_components'] as $address_component){
						switch($address_component['types'][0]){
							case 'street_number':
								$streetNo = $address_component['long_name'];
								break;
							case 'route':
								$street = $address_component['long_name'];
								break;
							case 'locality':
								$model->suburb=$address_component['long_name'];
								break;
							case 'administrative_area_level_1':
								$model->state=$address_component['short_name'];
								break;
							case 'country':
								$model->country=$address_component['long_name'];
								break;
							case 'postal_code':
								$model->postcode=$address_component['long_name'];
								break;
						}
					}
					if($street){
						$model->street=$streetNo?($streetNo.' '.$street):$street;
					}
					$latlon=$result['geometry']['location'];
					$model->latitude=$latlon['lat'];
					$model->longitude=$latlon['lng'];

					Yii::app()->user->setFlash('coffee_update','<p>Geo information updated!</p>'
					.'<p>Old address was: '.$oldAddress.'</p>'
					.'<p>Please review the data and save it to make it persist!</p>');
				}else{
					Yii::app()->user->setFlash('coffee_update','Cannot update Geo information!  Check the address');
				}
			}else{
				$model->timeUpdated=new CDbExpression('NOW()');
				$model->timeCreated=time();
				if($model->save()){
					$this->_log('CREATE', $model);
					$this->redirect(array('view','id'=>$model->id));
				}
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['additionAction'])){
			switch($_POST['additionAction']){
				case 'Create Lead':
					$flashMessage='';
					if(Yii::app()->zoho->createLeadFromCoffeeShop($model)){
						Yii::app()->user->setFlash('coffee_update','Leads is created!');
					}else{
						Yii::app()->user->setFlash('coffee_update','Faile to create leads!');
					}
					break;
				case 'Resend Welcome':
					$email=$model->email;
					$flashMessage='';
					$absUrl=$this->createAbsoluteUrl('coffeeShop/viewShop',array('id'=>$model->id));
					if(!empty($email)){
						Yii::app()->mailer->sendOutgoingMail('approveCafe',$email,'YOUR CAFE HAS BEEN NOMINTED AS A POTENTIAL TOP 100 IN MELBOURNE',
						array('absUrl'=>$absUrl,'name'=>$model->name));
						$flashMessage.='Email has been sent to '.$email.' to notify about this approval. ';
					}else{
						$flashMessage.='Email is empty, cannot send.';
					}
					Yii::app()->user->setFlash('coffee_update',$flashMessage);
					break;
				case 'Subscribe Manually':
					// subscribe as if the user had paid
					//code from SubscribeController - update both if needed
					$subscribe=new CafeOwnerSubscribe('ipn');
					$subscribe->shopId=$model->id;
					//$subscribe->txn_id='';
					$now=time();
					$period=1;
					$subscribe->startDate=$now;
					$subscribe->endDate=$now + $period * 60 * 60 * 24 * 366;
					$subscribe->save();
					break;
			}
		}elseif(isset($_POST['CoffeeShop']))
		{
			if(isset($_POST['geo'])){
				$address=$model->street.', '.$model->suburb.' '.$model->state.', '.$model->postcode.', '.$model->country;
				$geo=Yii::app()->google->getGeoCode($address);
				if($geo['status']=='OK'){
					$result=$geo['results'][0];
					$oldAddress=$model->street.', '.$model->suburb.' '.$model->postcode.' '.$model->state.', '.$model->country
					.'. Location: '.$model->latitude.' '.$model->longitude;
					$streetNo='';
					$street='';
					foreach($result['address_components'] as $address_component){
						switch($address_component['types'][0]){
							case 'street_number':
								$streetNo = $address_component['long_name'];
								break;
							case 'route':
								$street = $address_component['long_name'];
								break;
							case 'locality':
								$model->suburb=$address_component['long_name'];
								break;
							case 'administrative_area_level_1':
								$model->state=$address_component['short_name'];
								break;
							case 'country':
								$model->country=$address_component['long_name'];
								break;
							case 'postal_code':
								$model->postcode=$address_component['long_name'];
								break;
						}
					}
					if($street){
						$model->street=$streetNo?($streetNo.' '.$street):$street;
					}
					$latlon=$result['geometry']['location'];
					$model->latitude=$latlon['lat'];
					$model->longitude=$latlon['lng'];

					Yii::app()->user->setFlash('coffee_update','<p>Geo information updated!</p>'
					.'<p>Old address was: '.$oldAddress.'</p>'
					.'<p>Please review the data and save it to make it persist!</p>');
				}else{
					Yii::app()->user->setFlash('coffee_update','Cannot update Geo information!  Check the address');
				}
			}else{
				$beforeSummary=$model->toSummaryString();
				$model->attributes=$_POST['CoffeeShop'];

				if(isset($_POST['copy_day1'])){
					$model->copyTimeFromDay1();
				}
				$lastUpdated=strtotime($model->timeUpdated);
				$model->timeUpdated=new CDbExpression('NOW()');
				if($model->save()){
					$this->_log('UPDATE', array($beforeSummary,$model));
					if($this->twitterOnUpdate && $model->showWeb  && $lastUpdated<(time()-60*60*12)){
						$absUrl=$this->createAbsoluteUrl('coffeeShop/viewShop',array('id'=>$model->id));
						$twitterSent=Yii::app()->twitter->setStatus("Cafe is updated! See latest info about {$model->name}, {$model->suburb} {$model->state} at $absUrl");
					}
					if($model->ownerId){
						$authManager=Yii::app()->authManager;
						if(!$authManager->isAssigned('cafeOwner',$model->ownerId)){
							$authManager->assign('cafeOwner',$model->ownerId);
						}
					}
					$this->redirect(array('view','id'=>$model->id));
				}
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	public function actionOwnerUpdate()
	{

		$model=$this->loadModel();

		if(!Yii::app()->user->checkAccess('cafeOwnerSubscribe',array('shop'=>$model))){
			throw new CHttpException(403,'You cannot edit this cafe now');
		}

		$model->scenario='ownerUpdate';
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['CoffeeShop']))
		{
			$model->attributes=$_POST['CoffeeShop'];

			$lastUpdated=strtotime($model->timeUpdated);
			$time=time();
			$model->timeUpdated=new CDbExpression('NOW()');
			if($model->save()){
				if($this->twitterOnUpdate && $model->showWeb && $lastUpdated<(time()-60*60*12) ){
					$absUrl=$this->createAbsoluteUrl('coffeeShop/viewShop',array('id'=>$model->id));
					$twitterSent=Yii::app()->twitter->setStatus("Cafe is updated! See latest info about {$model->name}, {$model->suburb} {$model->state} at $absUrl");
				}
				@Yii::app()->mailer->sendOutgoingMail('alertEmail',Yii::app()->params['alertEmail'],'Auto Alert: cafe update',
				array(
					'event'=>array(
						'event'=>'Cafe updated by owner',
						'name'=>$model->name
				)
				));
				$this->redirect(array('ownerUpdate','id'=>$model->id));
			}
		}

		$this->render('ownerUpdate',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model=$this->loadModel();
			$this->_log('DELETE', $model);
			//$model->delete();
			$model->deleted=1;
			$model->timeUpdated=new CDbExpression('NOW()');
			$model->save();
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_POST['ajax'])){
				$this->redirect(array('index'));
			}
		}
		else
		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('CoffeeShop');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new CoffeeShop('search');
		$model->showWeb=null;
		$model->showIphone=null;
		$model->hotshot=null;
		$model->beanRating=null;
		$model->hotChocolate=null;
		$model->top100=null;
		$model->upgraded=null;
		$model->deleted=0;
		if(isset($_GET['CoffeeShop']))
		$model->attributes=$_GET['CoffeeShop'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	public function actionManageImages(){
		$this->checkOwnerEditing();
		$model=$this->loadModel();
		if(Yii::app()->user->checkAccess('admin')){
			$imageDataProvider=CoffeeShopImage::model()->searchByShop($model->id);
		}else{
			$imageDataProvider=CoffeeShopImage::model()->publicOnly()->searchByShop($model->id);
			
		}
		$this->render('manageImages',array(
			'model'=>$model,
			'imageDataProvider'=>$imageDataProvider
		));
	}

	public function actionDeleteImage(){

		if(isset($_GET['id']))
		$model=CoffeeShopImage::model()->findbyPk($_GET['id']);

		if($model===null)
		throw new CHttpException(404,'The requested page does not exist.');

		$this->checkOwnerEditing(CoffeeShop::model()->findbyPk($model->shopId));

		if(Yii::app()->user->checkAccess('admin')||$model->uploadedBy==Yii::app()->user->getId()){


			$shopId=$model->shopId;
			if($model->delete()){
				$rootPath=dirname(Yii::app()->basePath);
				@unlink($rootPath.$model->filePath);
				@unlink($rootPath.$model->thumbPath);
			}

			$this->redirect(array('manageImages','id'=>$shopId));
		}else{
			throw new CHttpException(403,'You can only delete the photo you uploaded.');
		}
	}

	public function actionUploadImage(){
		$this->checkOwnerEditing();
		$coffeeShop=$this->loadModel();

		$model=new CoffeeShopImage;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['CoffeeShopImage']))
		{
			$model->attributes=$_POST['CoffeeShopImage'];
			$model->shopId=$coffeeShop->id;
			if($this->saveImages($model)){

				$model->uploadIp=$_SERVER['REMOTE_ADDR'];
				$model->uploadTime=time();
				$model->uploadedBy=Yii::app()->user->getId();

				if($model->save()){
					$coffeeShop->timeUpdated=new CDbExpression('NOW()');
					$coffeeShop->save();
					$this->redirect(array('manageImages','id'=>$coffeeShop->id));
				}
			}
		}

		$this->render('uploadImage',array(
			'model'=>$model,
			'coffeeShop'=>$coffeeShop
		));
	}
	public function actionQuickCreateUser()
	{
		$model=new User('quickcreate');
		$profile=new Profile;
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->activkey=Yii::app()->User->encrypting(microtime().$model->password);
			$model->createtime=time();
			$model->lastvisit=time();
			$profile->attributes=$_POST['Profile'];
			$profile->user_id=0;
			if($model->validate()&&$profile->validate()) {
				$model->password=Yii::app()->User->encrypting($model->password);
				if($model->save()) {
					$profile->user_id=$model->id;
					$profile->save();
					$shop=null;
					if(!empty($_POST['coffeeShopId'])){
						$shop=CoffeeShop::model()->findbyPk($_POST['coffeeShopId']);
						if($shop){
							$shop->ownerId=$model->id;
							$shop->save();
							$authManager=Yii::app()->authManager;
							if(!$authManager->isAssigned('cafeOwner',$model->id)){
								$authManager->assign('cafeOwner',$model->id);
							}
							$this->redirect(array('view','id'=>$shop->id));
							return;
						}
					}
					$this->_log('CREATE USER '.$model->id, $shop);
					$this->redirect(array('/user/user/view','id'=>$model->id));
					return;

				}
			}
		}

		$this->render('quickcreateuser',array(
			'model'=>$model,
			'profile'=>$profile,
		));
	}
	public function actionAjaxQuickSearch(){
		if(Yii::app()->request->isAjaxRequest && isset($_GET['term']))
		{
			/* q is the default GET variable name that is used by
			 / the autocomplete widget to pass in user input
			 */
			$name = $_GET['term'];
			// this was set with the "max" attribute of the CAutoComplete widget
			$limit = isset($_GET['limit'])?min($_GET['limit'], 50):50;
			$criteria = new CDbCriteria;
			$criteria->condition = "name LIKE :sterm AND (ownerId=0 OR ownerId is null)";
			$criteria->params = array(":sterm"=>"%$name%");
			$criteria->limit = $limit;
			$userArray = CoffeeShop::model()->findAll($criteria);
			$returnVal = array();
			foreach($userArray as $cafe)
			{
				$returnVal[] =array('label'=> $cafe->getAttribute('name'),
				//'value'=>$cafe->getAttribute('id'),
				'id'=>$cafe->getAttribute('id')
				);
			}
			//          header("Cache-Control: no-cache, must-revalidate");
			//          header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
			echo CJSON::encode($returnVal);
		}

	}
	public function actionAjaxQuickSearchUser(){
		if(Yii::app()->request->isAjaxRequest && isset($_GET['term']))
		{
			/* q is the default GET variable name that is used by
			 / the autocomplete widget to pass in user input
			 */
			$name = $_GET['term'];
			// this was set with the "max" attribute of the CAutoComplete widget
			$limit = isset($_GET['limit'])?min($_GET['limit'], 50):50;
			$criteria = new CDbCriteria;
			$criteria->condition = "username LIKE :sterm OR email like :sterm";
			$criteria->params = array(":sterm"=>"%$name%");
			$criteria->limit = $limit;
			$userArray = User::model()->findAll($criteria);
			$returnVal = array();
			foreach($userArray as $user)
			{
				$returnVal[] =array('label'=> $user->getAttribute('username').
				'('.$user->getAttribute('email').')',
				'id'=>$user->getAttribute('id')."\n");
			}
			//          header("Cache-Control: no-cache, must-revalidate");
			//          header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
			echo CJSON::encode($returnVal);
		}

	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @return CoffeeShop
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
			$this->_model=CoffeeShop::model()->findbyPk($_GET['id']);
			if($this->_model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='coffeeshop-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	private function checkOwnerEditing($model=null){
		if(Yii::app()->user->checkAccess('photoManager')){
			return true;
		}
		if(!$model){
			$model=$this->loadModel();
		}
		//$current=Yii::app()->user->getId();
		//		if($model && $model->ownerId==$current){
		//			return true;
		//		}
		if(Yii::app()->user->checkAccess('cafeOwnerSubscribe',array('shop'=>$model))){
			return true;
		}

		throw new CHttpException(403,'You cannot manage this cafe.');
	}

	private function saveImages($model){
		$uploadImage=CUploadedFile::getInstance($model,'imageUpload');
		if($uploadImage!==null){
			$thumbImage=CUploadedFile::getInstance($model,'thumbUpload');

			$extension=substr($uploadImage->getName(),strrpos($uploadImage->getName(),'.'));
			$fileName=uniqid($model->shopId.'_').$extension;

			$rootPath=dirname(Yii::app()->basePath);
			$fileFullPath='/images/'.$this->imageFolder.'/'.$fileName;
			$fileThumbPath='/images/'.$this->imageFolder.'/'.
			$this->thumbFolder.'/'.$fileName;

			if($thumbImage!==null){
				$image = Yii::app()->image->load($uploadImage->getTempName());
				$image->resize($this->imageWidth,$this->imageHeight);
				$imageThumb = Yii::app()->image->load($thumbImage->getTempName());
				$imageThumb->resize($this->thumbWidth,$this->thumbHeight);
				//if($thumbImage->saveAs($rootPath.$fileThumbPath)&&$uploadImage->saveAs($rootPath.$fileFullPath)){
				if($image->save($rootPath.$fileFullPath,false)&&$imageThumb->save($rootPath.$fileThumbPath,false)){
					$model->filePath=$fileFullPath;
					$model->thumbPath=$fileThumbPath;
					return true;
				}
			}else{
				$image = Yii::app()->image->load($uploadImage->getTempName());
				$image->resize($this->imageWidth,$this->imageHeight);
				if($image->save($rootPath.$fileFullPath,false)){
					$imageThumb = Yii::app()->image->load($uploadImage->getTempName());
					$imageThumb->resize($this->thumbWidth,$this->thumbHeight);
					if($imageThumb->save($rootPath.$fileThumbPath,false)){
						$model->filePath=$fileFullPath;
						$model->thumbPath=$fileThumbPath;
						return true;
					}
				}
			}
			@unlink($rootPath.$fileFullPath);
			@unlink($rootPath.$fileThumbPath);
		}
		return false;
	}

	protected function _log($action,$shop,$category='mcr.coffeeshop.action'){
		$user=Yii::app()->user;
		$message='';
		if($user->isGuest){
			$message.='Guest User ';
		}else{
			$currentUser=User::model()->findByPk($user->id);
			$message.='User: '.$currentUser->username.' ('.$currentUser->id.') '."\n";
		}
		$message.=' performed action: '.$action ."\n";
		$message.='with cafe(s):';
		if(is_array($shop)){
			foreach ($shop as $aShop){
				if(is_object($aShop)){
					$message.=$aShop->toSummaryString()."\n";
				}else{
					$message.=$aShop."\n";
				}
			}
		}else{
			if($shop){
				if(is_object($shop)){
					$message.=$shop->toSummaryString()."\n";
				}else{
					$message.=$shop."\n";
				}
			}
		}
		Yii::log($message, $level=CLogger::LEVEL_INFO,$category);
	}
	
	
	
	public function actionExportFile() {
		
		$model=new CoffeeShopExportSearchForm();

		if(isset($_POST['CoffeeShopExportSearchForm']))
		{
			$model->attributes = $_POST['CoffeeShopExportSearchForm'];
			$model->paymentDateStart = $model->paymentDateStart/1000;
			$model->paymentDateEnd = $model->paymentDateEnd/1000;
			
			/** Set rules for filter. **/
			//if payment search date is specifed, then the subsribed and claimed will be set to 1 even was not 1.
			if ($model->subscribed != DataUtil::VALUE_NO
					&& $model->claimed != DataUtil::VALUE_NO
					&& (!empty($model->paymentDateStart) || !empty($model->paymentDateEnd))){
				$model->subscribed = DataUtil::VALUE_YES;
				$model->claimed = DataUtil::VALUE_YES;
			}
			
			
			//if owner name and owner email is specified, then the claimed will be set to 1 even was note 1.
			if (trim($model->claimed) == ''
				&& (!empty($model->ownerName) || !empty($model->ownerEmail) || trim($model->subscribed) != ''))
				$model->claimed = DataUtil::VALUE_YES;
			/** End of Rules **/
			
			//Set up basic for SQL.
			$select = array('s.name as cafe_name','s.street as cafe_street','s.suburb as cafe_suburb','s.city as cafe_city',
				's.state as cafe_state', 's.postcode as cafe_postcode', 's.country as cafe_country',
				's.phone as cafe_phone','s.website as cafe_website','s.email as cafe_email', 
				's.ownerName as owner_name','u.email as owner_email','u.mobile as owner_mobile');
			
			$from = 'mcr_coffeeshop s';
			$where = array('and');
			
			if (!empty($model->coffeeShopName))
				$where[]='s.name LIKE "%'.trim($model->coffeeShopName).'%"';
				
			if (!empty($model->suburb))
				$where[]='s.suburb LIKE "%'.trim($model->suburb).'%"';
				
			if (!empty($model->state))
				$where[]='s.state LIKE "%'.trim($model->state).'%"';
			
			// if want shops that are claimed.
			if ($model->claimed == DataUtil::VALUE_YES) {
				$where[]='s.ownerId IS NOT NULL';
				
				//check if owername is specifed.
				if (!empty($model->ownerName))
					$where[] = 's.ownerName LIKE "%'.trim($model->ownerName).'%"';
				
				//check if owername is specifed.
				if (!empty($model->ownerEmail))
					$where[] = 'u.email LIKE "%'.trim($model->ownerEmail).'%"';
					
				//if want shop that are subscribed.
				if ($model->subscribed == DataUtil::VALUE_YES){					
					// add two columns
					$select[] = 'FROM_UNIXTIME(cs.startDate) as payment_date';
					$select[] = 'pt.mc_gross as payment_amount';

					$where[]='cs.startDate <= UNIX_TIMESTAMP(NOW())';
					$where[]='cs.endDate >= UNIX_TIMESTAMP(NOW())';
					
					//check if the payment start date is specified.
					if(!empty($model->paymentDateStart))
						$where[]='cs.startDate >= '.$model->paymentDateStart;
					
					//check if the payment end date is specifed.
					if (!empty($model->paymentDateEnd))
						$where[]='cs.startDate <= '.$model->paymentDateEnd;
				}
				
				// if want shop that are not subscribed.
				if ($model->subscribed == DataUtil::VALUE_NO){	
					$where[]='cs.endDate < UNIX_TIMESTAMP(NOW()) OR cs.startDate IS NULL';
				}
			}
			
			// if want to know shops that are not claimed
			if($model->claimed == DataUtil::VALUE_NO){
				$where[]='s.ownerId IS NULL';
			}
			
			// If vote period is set, add new column in exported file.
			if ($model->votePeriod)
				$select[]='v.vote';
			
			// Start to build SQL.
			$command = Yii::app()->db->createCommand()
				->select($select)
				->from($from)
				->leftJoin('mcr_users u','s.ownerId = u.id');
				
			// if want to know the subscribed, then two talbes should be joined.
			if ($model->claimed == DataUtil::VALUE_YES && $model->subscribed != '')
				$command = $command->leftJoin('mcr_cafeownersubscribe cs', 's.id = cs.shopId')
								   ->leftJoin('mcr_paypaltransaction pt','cs.txn_id = pt.txn_id');
			
			// If vote period is set, add new column in exported file.
			if ($model->votePeriod)
				$command = $command->leftJoin('(select voteId, count(1) as vote from mcr_cafevote where period = "'.$model->votePeriod.'" group by voteId) v', 'v.voteId = s.Id');
			
			// check if any where condition is specified.
			if (count($where)>1)
				$command = $command->where($where);
			
// echo $command->text;exit;
			
			$results = $command->queryAll();
// var_dump($results);exit;
			$labels = array('Cafe Name', 'Street', 'Suburb', 'City', 'State', 'Postcode', 'Country',
				'Cafe Phone', 'Cafe Website', 'Cafe Email', 'Owner', 'Owner Email', 'Owner Mobile');
			
			// If vote period is set, add new column in exported file.
			if ($model->subscribed){
				$labels[] = 'Payment Date';
				$labels[] = 'Payment Amount';
			}
			
			// If vote period is set, add new column in exported file.
			if ($model->votePeriod)
				$labels[]='Vote - '.$model->votePeriod;
			
			$out = fopen('php://output', 'w');
			header("Content-type: application/vnd.ms-excel");
			header("Content-Disposition: attachment; filename=cafe_".date('Ymd').".csv" );
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
			header("Pragma: public");		
			fputcsv($out, $labels);
			foreach ($results as $result){
				fputcsv($out, $result);
			}
			fclose($out);
			exit;
		}

		$this->render('exportFile',array(
			'model'=>$model,
		));
	}

	public function actionAjaxQuickSearchHasOwner(){
		if(Yii::app()->request->isAjaxRequest && isset($_GET['term'])){
			$term = $_GET['term'];
			$cafes = CoffeeShop::model()->findAll(
				array(
					'select'=>'id,name',
					'condition'=>'name LIKE :term AND ownerId IS NOT NULL AND ownerId != 0',
					'params'=>array(":term"=>"%$term%")
				)
			);
			$results = array();
			foreach($cafes as $cafe)
			{
				$results[] =array(
					'id'=>$cafe->id,
					'label'=> $cafe->name,
				);
			}
			echo CJSON::encode($results);
		}
	}
}